#pragma once

#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <cerrno>
#include <cstring>
#include <cstdlib>

using namespace std;

const char *pathname = "/home/me/code/SharedMemory";
const int proj_id = 0001;
const int defaultsize = 4096; // 字节

key_t GetShmKeyOrDie()
{
    key_t k = ftok(pathname, proj_id);
    if (k < 0)
    {
        cerr << "ftok失败,errno:" << errno << ", error strng:" << strerror(errno) << endl;
        exit(1);
    }
    return k;
}

int CreateShmOrDie(key_t key, int size, int flag)
{
    int shmid = shmget(key, size, flag);
    if (shmid < 0)
    {
        cerr << "ftok失败,errno:" << errno << ", error strng:" << strerror(errno) << endl;
        exit(2);
    }
    return shmid;
}

int CreateShm(key_t key, int size)
{
    // IPC_CREAT:存在就获取，不存在就创建
    // IPC_EXCL:单独使用无意义
    // IPC_CREAT | IPC_EXCL:不存在就创建，存在就出错返回
    return CreateShmOrDie(key, size, IPC_CREAT | IPC_EXCL | 0666);
}

int GetShm(key_t key, int size)
{
    return CreateShmOrDie(key, size, IPC_CREAT);
}

void DeleteShm(int shmid)
{
    int n = shmctl(shmid, IPC_RMID, nullptr);
    if (n < 0)
    {
        cerr << "shmctl error" << endl;
    }
    else
    {
        cout << "shmctl sucess, shmid: " << shmid << endl;
    }
}

void *ShmAttch(int shmid)
{
    void *addr = shmat(shmid, nullptr, 0);
    if ((long long int)addr == -1)
    {
        cerr << "shmat error" << endl;
        return nullptr;
    }
    return addr;
}

void ShmDetach(void *addr)
{
    int n = shmdt(addr);
    if (n < 0)
    {
        cerr << "shmdrt error" << endl;
    }
}